package net.xdclass.online_xdclass.service.Impl;

import net.xdclass.online_xdclass.exception.XDException;
import net.xdclass.online_xdclass.mapper.*;
import net.xdclass.online_xdclass.model.entity.Episode;
import net.xdclass.online_xdclass.model.entity.PlayRecord;
import net.xdclass.online_xdclass.model.entity.Video;
import net.xdclass.online_xdclass.model.entity.VideoOrder;
import net.xdclass.online_xdclass.service.VideoOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author kingtao
 * @date 2022/3/6
 */
@Service
public class VideoOrderServiceImpl implements VideoOrderService {

    @Resource
    private VideoOrderMapper videoOrderMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private EpisodeMapper episodeMapper;

    @Resource
    private VideoMapper videoMapper;

    @Resource
    private PlayRecordMapper playRecordMapper;
    /**
     * 下单操作
     * 未来版本：抵扣优惠卷、风控用户检测、生成订单基础信息、生成支付信息
     * @author kingtao
     * @date 2022/3/6
     */
    @Override
    @Transactional
    public int save(int userId, int videoId) {
        //  判断用户是否购买
        VideoOrder videoOrder = videoOrderMapper.findByUserIdAndVideoIdAndState(userId, videoId, 1);
        if( videoOrder != null ) {
            return 0;
        }

        Video video = videoMapper.findById(videoId);
        VideoOrder newVideoOrder = new VideoOrder();
        newVideoOrder.setCreateTime(new Date());
        newVideoOrder.setOutTradeNo(UUID.randomUUID().toString());
        newVideoOrder.setState(1);
        newVideoOrder.setTotalFee(video.getPrice());
        newVideoOrder.setUserId(userId);
        newVideoOrder.setVideoId(videoId);
        newVideoOrder.setVideoImg(video.getCoverImg());
        newVideoOrder.setVideoTitle(video.getTitle());

        int rows = videoOrderMapper.saveOrder(newVideoOrder);

        //  设置生产播放记录
        if(rows == 1) {
            Episode episode = episodeMapper.findFirstEpisodeByVideoId(videoId);
            if(episode == null) {
                throw new XDException(-1, "视频没有集信息，请运营人员检查");
            }
            PlayRecord playRecord = new PlayRecord();
            playRecord.setCreateTime(new Date());
            playRecord.setVideoId(videoId);
            playRecord.setUserId(userId);
            playRecord.setEpisodeId(episode.getId());
            playRecord.setCurrentNum(episode.getNum());
            playRecordMapper.saveRecord(playRecord);
        }
        return rows;
    }

    @Override
    public List<VideoOrder> listOrderById(Integer userId) {
        return videoOrderMapper.listOrderById(userId);
    }
}
